﻿using System;
using System.Collections;
using System.Collections.Generic;
using IDAL;
using Model;
using Util;

namespace BLL
{
    /// <summary>
    /// 资源业务逻辑层
    /// </summary>
    public class ResourceService
    {
        private static readonly IResourceDAL dal = DALFactory.DataAccess.createResourceDAL();
        private static readonly IKeywordDAL keydal = DALFactory.DataAccess.createKeywordDAL();
        private static readonly ICategoryDAL categoryDal = DALFactory.DataAccess.createCategoryDAL();
        private static readonly ICommentDAL commentDal = DALFactory.DataAccess.createCommentDAL();

        //上传
        public Hashtable uploadResource(
                                        string resourceName,    /* 资源名称 */
                                        User uploader,          /* 上传者 */
                                        int categoryId,         /* 所属分类的ID*/
                                        string keywords,        /* 关键字,未分割 */
                                        string fileName,        /* 文件名 */
                                        string physicalPath,    /* 保存路径 */
                                        string transformPath,   /* 转换路径 */
                                        string description,     /* 资源描述 */
                                        int departmentId,       /* 课下载的部门 */
                                        int type                /* 类型 */
                                        )
        {
            Hashtable ht = new Hashtable();

            CategoryService cs = new CategoryService();

            Resource resource = new Resource()
            {
                resourceName = resourceName,
                uploader = uploader,
                uploadTime = DateTime.Now,
                category = cs.getCategoryById(categoryId),
                fileName = fileName,
                physicalPath = physicalPath,
                transformPath = transformPath,
                description = description,
                status = 0, /* 未审核 */
                downloadTimes = 0, /* 下载次数初始化为0 */
                marks = 3, /* 评分初始化为0 */
                marksUserNum = 1,/* 评分人数 */
                lastModifyTime = DateTime.Now,
                lastModifyUser = null,
                departmentId = departmentId,
                type = type
            };
            try
            {
                resource = dal.saveResouce(resource);
            }
            catch (Exception e)
            {
                ht.Add("result", "0");
                ht.Add("message", e.Message);
                return ht;
            }
            KeywordService ks = new KeywordService();
            ks.saveKeyword(keywords, resource.id);
            IList<Keyword> keywordList = ks.getKeywords(resource);
            resource.keywords = keywordList;
            dal.updateResouce(resource);
            ht.Add("result", "1");
            ht.Add("message", "上传成功");
            ht.Add("resource", resource);
            return ht;
        }

        //更新 未测试
        public Hashtable updateResource(
                                        int id,
                                        string resourceName,    /* 资源名称 */
                                        User user,              /* 更新者 */
                                        int categoryId,         /* 所属分类的ID*/
                                        string keywords,        /* 关键字,未分割 */
                                        string description,     /* 资源描述 */
                                        int departmentId        /* 可下载部门 */
                                        )
        {
            Hashtable ht = new Hashtable();
            Resource resource = getResourceById(id);
            if (resource == null)
            {
                ht.Add("result", "0");
                ht.Add("message", "资源不存在");
                return ht;
            }

            CategoryService cs = new CategoryService();

            resource.resourceName = resourceName;
            resource.lastModifyUser = user;
            resource.lastModifyTime = DateTime.Now;
            resource.category = cs.getCategoryById(categoryId);
            resource.description = description;
            resource.departmentId = departmentId;

            new KeywordService().delKeywords(id);
            KeywordService ks = new KeywordService();
            ks.saveKeyword(keywords, resource.id);
            IList<Keyword> keywordList = ks.getKeywords(resource);
            resource.keywords = keywordList;
            dal.updateResouce(resource);

            ht.Add("result", "1");
            ht.Add("message", "修改成功");
            return ht;
        }

        //删除
        public Hashtable deleteResource(int id)
        {
            Hashtable ht = new Hashtable();
            Resource resource = getResourceById(id);
            if (ht == null)
            {
                ht.Add("result", "0");
                ht.Add("message", "资源不存在");
                return ht;
            }
            try
            {
                dal.deleteResource(resource);
            }
            catch (Exception e)
            {
                ht.Add("result", "0");
                ht.Add("message", e.Message);
            }

            ht.Add("result", "1");
            ht.Add("message", "删除成功");
            return ht;
        }

        //审核资源
        public Hashtable censorResource(int id, int status, string reason = "")
        {
            Hashtable ht = new Hashtable();
            Resource resource = getResourceById(id);
            if (ht == null)
            {
                ht.Add("result", "0");
                ht.Add("message", "资源不存在");
                return ht;
            }

            resource.status = status; /* -1或者1 表示拒绝或者通过 */
            try
            {
                dal.updateResouce(resource);
            }
            catch (Exception e)
            {
                ht.Add("result", "0");
                ht.Add("message", e.Message);
                return ht;
            }
            ht.Add("result", "1");
            ht.Add("message", "审查成功");
            //发送通知
            if (status == -1)
            {
                new NoticeService().publishNotice(resource.uploader, "您的资源《" + resource.resourceName + "》审核失败：" + reason);
            }
            else
            {
                NoticeService ns = new NoticeService();
                UserRelationService urs=new UserRelationService();
                IList<UserRelation> murl = new UserRelationService().GetUserRelationsFollow(resource.uploader.username);
                foreach (UserRelation f in murl)
                {
                    ns.publishNotice(f.who, "用户 "+resource.uploader.name + " 新上传了知识，快去他的空间看看吧！");
                }
                
                //ns.publishNotice();
            }
            return ht;

        }

        //查看资源列表 所有
        public List<Resource> getAllResources()
        {
            IList<Resource> resources = new List<Resource>();
            resources = dal.getAllResource();
            List<Resource> ree = (List<Resource>)resources;
            ree.Reverse();
            return ree;
        }

        //查看资源列表 审核
        public IList<Resource> getCensoredReources()
        {
            IList<Resource> resources = new List<Resource>();
            resources = dal.getResourceByState(1);
            return resources;
        }

        //查看资源列表 未审核
        public IList<Resource> getUncensoredReources()
        {
            IList<Resource> resources = new List<Resource>();
            resources = dal.getResourceByState(0);
            return resources;
        }

        //查看资源列表 根据目录
        public IList<Resource> getResourceByCategory(int categoryId)
        {
            Category category = categoryDal.getCategory(categoryId);
            IList<Resource> resources = new List<Resource>();
            resources = dal.getRourceByCategory(category);
            return resources;
        }

        //查看资源列表 根据KeyWord
        public IList<Resource> getResourceByKeyword(string keyword)
        {
            IList<Keyword> kwl = keydal.getResourceListByKeyword(keyword);
            IList<Resource> rel = new List<Resource>();
            foreach (Keyword k in kwl)
            {
                rel.Add(this.getResourceById(k.resource.id));
            }

            return rel;
        }

        //根据ID查看资源
        public Resource getResourceById(int id)
        {
            return dal.getResouceById(id);
        }

        //根据用户查看资源
        public IList<Resource> getResourceByUser(User user)
        {
            return dal.getUserResouce(user);
        }

        //搜索资源
        public Hashtable searchResource(string queryStr, int isFulltext)
        {
            Hashtable ht = new Hashtable();
            IList<Resource> resourceList = new List<Resource>();
            if (isFulltext == 0) //只搜索标题和描述
            {
                resourceList = dal.searchResource(queryStr);
                ht.Add("isFulltext", "0");
                ht.Add("resourceList", resourceList);
                return ht;
            }
            else //全文检索
            {
                Hashtable result = SearchUtil.searchDocument(queryStr, "<span class='highlight'>", "</span>", 200);
                ht.Add("isFulltext", "1");
                //处理返回的结果集
                Hashtable processResult = processLuceneResult(result);
                if ("0" == (string)processResult["result"])
                {
                    ht.Add("result", "0");
                    return ht;
                }
                ht.Add("result", "1");
                ht.Add("resourceList", processResult["resourceList"]);
                ht.Add("contentList", processResult["contentList"]);
                return ht;
            }
        }

        //猜你喜欢 未实现
        public IList<Resource> getLovedResource(User user)
        {
            return null;
        }

        //更新评分
        public Hashtable markResource(int resourceId, int marks)
        {
            Hashtable ht = new Hashtable();
            Resource resource = getResourceById(resourceId);
            if (ht == null)
            {
                ht.Add("result", "0");
                ht.Add("message", "资源不存在");
                return ht;
            }
            resource.marks += marks;
            resource.marksUserNum++;
            try
            {
                dal.updateResouce(resource);
            }
            catch (Exception e)
            {
                ht.Add("result", "0");
                ht.Add("message", e.Message);
            }
            ht.Add("result", "1");
            ht.Add("message", "评分成功");
            return ht;
        }

        //发表评论
        public Hashtable sendComment(
                                        User user,             /* 发表评论用户 */
                                        int resourceId,            /* 资源Id */
                                        string content         /* 评论内容 */
                                    )
        {
            Hashtable ht = new Hashtable();

            Comment comment = new Comment()
            {
                user = user,
                resource = new ResourceService().getResourceById(resourceId),
                content = content,
                commentTime = DateTime.Now
            };


            try
            {
                commentDal.saveComment(comment);
            }
            catch (Exception e)
            {
                ht.Add("result", "0");
                ht.Add("message", e.Message);
                return ht;
            }
            ht.Add("result", "1");
            ht.Add("message", "评论成功");
            return ht;
        }

        //删除评论
        public Hashtable deleteComment(int id)
        {
            Hashtable ht = new Hashtable();
            Comment comment = commentDal.getCommentById(id);
            if (comment == null)
            {
                ht.Add("result", "0");
                ht.Add("message", "资源不存在");
                return ht;
            }
            try
            {
                commentDal.deleteComment(comment);
            }
            catch (Exception e)
            {
                ht.Add("result", "0");
                ht.Add("message", e.Message);
            }

            ht.Add("result", "1");
            ht.Add("message", "删除成功");
            return ht;

        }

        //查看该资源所有评论
        public IList<Comment> getResourceComment(int resourceId)
        {
            Resource resource = dal.getResouceById(resourceId);
            IList<Comment> comments = new List<Comment>();
            comments = commentDal.getResourceComment(resource);
            return comments;
        }

        //查看用户的所有评论
        public IList<Comment> getUserComment(int userId)
        {
            User user = new UserService().getUserById(userId);

            IList<Comment> comments = new List<Comment>();
            comments = commentDal.getUserComment(user);
            return comments;
        }

        //处理全文检索返回的结果
        private Hashtable processLuceneResult(Hashtable luceneResult)
        {
            Hashtable ht = new Hashtable();
            string result = (string)luceneResult["result"];
            if (result == "0")
            {
                ht.Add("result", "0");
                return ht;
            }

            IList<Resource> resourceList = new List<Resource>();
            IList<string> contentList = new List<string>();

            string indexIdStr = (string)luceneResult["indexIdStr"];
            string searchContent = (string)luceneResult["searchContent"];
            string[] indexArray = indexIdStr.Split(new char[1] { '|' });
            string[] searchContentArray = searchContent.Split(new char[1] { '|' });
            for (int i = 0; i < indexArray.Length - 1; i++)
            {
                resourceList.Add(getResourceById(int.Parse(indexArray[i])));
                contentList.Add(searchContentArray[i]);
            }
            ht.Add("result", "1");
            ht.Add("resourceList", resourceList);
            ht.Add("contentList", contentList);
            return ht;
        }

        //分析关键字
        public IList<String> analyzeKeywors(string resourceName, string description)
        {
            return SearchUtil.segmentationWords2(resourceName + description);
        }

        //更新下载次数
        public void addDownloadTime(int resourceId)
        {
            Hashtable ht = new Hashtable();
            Resource resource = getResourceById(resourceId);
            resource.downloadTimes += 1;
            try
            {
                dal.updateResouce(resource);
            }
            catch (Exception e)
            {
                
            }
           
        }

    }
}
